<?php

namespace App\Http\Controllers\Admin\Manager;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Http\Requests\Admin\StoreUserPostRequest;

use App\Models\Admin\Admin;

class UserController extends Controller
{	
	public $module = 'managers_tag';

    public $parent_module = '';

    public $breadcrumb_name = 'managers';

    public $page_name = '管理员用户';

	public $page_describe = '';

    public function index()
    {
    	$admins = Admin::paginate(25);
    	return view('manager.user.index', compact('admins'));
    }

    public function create()
    {
    	$roles = \App\Models\Admin\Role::all();
    	return view('manager.user.create', compact('roles'));
    }

    public function store(StoreUserPostRequest $request)
    {
    	try {
    		$admin = new Admin;
    		$admin->name = $request['name'];
    		$admin->email = $request['email'];
    		$admin->password = bcrypt($request['password']);
    		$admin->save();
	        if (is_array($request->get('roles'))) {
                $admin->giveRolesTo($request->get('roles'));
            }
    		return redirect()->route('managers.index')->withSuccess('新增用户成功');
    	} catch (\Exception $e) {
    		return redirect()->back()->withErrors(array('error' => $e->getMessage()))->withInput();
    	}
    }

    public function show($id)
    {
        dd('不支持预览！');
    }

    public function edit($id)
    {	
    	$admin = Admin::find($id);
    	$roles = \App\Models\Admin\Role::all();
    	$roleArr = [];
        if ($admin->roles) {
            foreach ($admin->roles as $key) {
                $roleArr[] = $key->id;
            }
        }
    	return view('manager.user.edit', compact('admin', 'roles', 'roleArr'));
    }

    public function update(Request $request, $id)
    {
    	try {
    		$admin = Admin::find($id);
    		$admin->name = $request['name'];
    		$admin->save();
    		$admin->giveRolesTo($request->get('roles', []));
    		return redirect()->route('managers.index')->withSuccess('修改用户成功');
    	} catch (Exception $e) {
    		return redirect()->back()->withErrors(array('error' => $e->getMessage()));
    	}
    }

    public function destroy($id)
    {
    	try {
            $admin = Admin::find($id);
            if ($admin->delete()) {
                return redirect()->back()->withSuccess('删除用户成功');
            }
        } catch(\Exception $e) {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()));
        }
    }
}
